set(TARGET mxcube)

# #####################################
# building variables
# #####################################
# debug build?
set(DEBUG 1)

# optimization
set(OPT -O0)

# ######################################
# binaries
# ######################################
set(PREFIX arm-none-eabi-)

# 使用的 C 语言版本；
SET(CMAKE_C_STANDARD 99)

# 使用的 cpp 版本；
SET(CMAKE_CXX_STANDARD 17)

# The gcc compiler bin path can be either defined in make command via GCC_PATH variable (> make GCC_PATH=xxx)
# either it can be added to the PATH environment variable.
if($ENV{ARM_GCC_ROOT})
    set(CMAKE_C_COMPILER ${GCC_PATH}/${PREFIX}gcc)
    set(CMAKE_CXX_COMPILER ${GCC_PATH}/${PREFIX}g++)

    # set(CMAKE_ASM_COMPILER ${GCC_PATH}/${PREFIX}as)
    set(OBJCOPY ${GCC_PATH}/${PREFIX}objcopy)
    set(SIZE ${GCC_PATH}/${PREFIX}size)
else()
    set(CMAKE_C_COMPILER ${PREFIX}gcc)
    set(CMAKE_CXX_COMPILER ${PREFIX}g++)

    # set(CMAKE_ASM_COMPILER ${PREFIX}as)
    set(OBJCOPY ${PREFIX}objcopy)
    set(SIZE ${PREFIX}size)
endif()

set(CMAKE_EXECUTABLE_SUFFIX .elf)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)

set(HEX "${CP} -O ihex")
set(BIN "${CP} -O binary -S")

set(TOOLCHAIN "gnu")

# cpu
set(CPU "cortex-m4")

# fpu
set(FPU "fpv4-sp-d16")

# float-abi
set(FLOAT-ABI "hard")

# mcu
set(MCU -mcpu=${CPU} -mthumb -mthumb-interwork -mfloat-abi=${FLOAT-ABI} -mfpu=${FPU})

# C defines
add_definitions(
    -DUSE_HAL_DRIVER
    -DSTM32L496xx

    # -D__FPU_PRESENT=1
)

# compile gcc flags
list(APPEND AFLAGS ${MCU} ${OPT} -Wall -fdata-sections -ffunction-sections -x assembler-with-cpp)
list(APPEND CFLAGS ${MCU} ${OPT} -Wall -fdata-sections -ffunction-sections)

list(JOIN CFLAGS " " CFLAGS)
list(JOIN AFLAGS " " AFLAGS)

string(APPEND CMAKE_C_FLAGS "${CFLAGS} -specs=nosys.specs -fmessage-length=0")
string(APPEND CMAKE_CXX_FLAGS "${CFLAGS} -fno-exceptions")
string(APPEND CMAKE_ASM_FLAGS "${AFLAGS}")

list(APPEND LDFLAGS
    -mcpu=${CPU}
    -mthumb -mthumb-interwork
    -mfloat-abi=${FLOAT-ABI}
    -mfpu=${FPU}
    -Wl,--gc-sections
    -Wl,--cref
    -Wl,--print-memory-usage
    -flto -specs=nano.specs # -specs=nosys.specs # optimize options
)

message("${LDFLAGS}")

# # Generic compiler settings for optimization and basic link lib
# add_compile_options(-pipe ${MCU_FLAGS} -Wall -Werror -fmessage-length=0 # basic options
# -ffunction-sections -fdata-sections -fno-common # optimize options
# )

# set(MCU_FLAGS -mcpu=cortex-m4 -mthumb -mthumb-interwork -mfloat-abi=hard -mfpu=fpv4-sp-d16 -O0 -gdwarf-2 -g)

# add_compile_options(-pipe ${MCU_FLAGS} -Wall -Werror -fmessage-length=0 # basic options

# # -ffunction-sections #-fdata-sections #-fno-common # optimize options
# )